<template>
  <div v-if="layout.type" class="flex-center full" :style="layout.style" :class="layout.classList" @click.stop="onClick(layout)">
    {{ get1(layout) }}
  </div>
  <ElSplitter v-else-if="layout.component === 'split'" :style="layout.style" :key="splitLayout" :layout="splitLayout" :class="layout.classList" @click.stop="onClick(layout)">
    <template v-if="layout.children && layout.children.length > 0">
      <ElSplitterPanel v-for="(child, i) in layout.children" :key="i"
        :size="child.componentProps?.size"
        :min="child.componentProps?.min"
        :max="child.componentProps?.max"
        :resizable="child.componentProps?.resizable"
        :collapsible="child.componentProps?.collapsible"
      >
        <ContentView :layout="child" />
      </ElSplitterPanel>
    </template>
    <template v-else>{{ layout.content }}</template>
  </ElSplitter>
  <component v-else :is="layout.component || 'div'" :style="layout.style" :class="layout.classList" @click.stop="onClick(layout)">
    <template v-if="layout.children && layout.children.length > 0">
      <ContentView v-for="(child, i) in layout.children" :layout="child" :key="i" />
    </template>
    <template v-else>{{ layout.content }}</template>
  </component>
</template>
<script setup lang="ts">
  import { computed, inject, Ref } from 'vue';
  import { ContentView, TreeViewType } from '..';
  import { Layout } from '@/views/types';
  import { ElSplitter, ElSplitterPanel } from 'element-plus';
  
  const props = defineProps<{layout}>()

  const treeViewRef = inject<Ref<TreeViewType>>('treeViewRef', void 0)
  const layout = computed(() => {
    const layout = props.layout
    if(!layout) return void 0

    layout.classList = []
    if(layout.cls) for(const item of layout.cls) layout.classList.push(item)
    if(layout.id === treeViewRef.value?.getCurrentArea()?.id) layout.classList.push('selected')

    return layout
  })

  const splitLayout = computed(() => layout.value?.componentProps?.layout)

  function get1(layout: Layout) {
    const { type, component, componentProps } = layout
    if(!type || !component) return ''

    if(!componentProps) return `【${component}】`

    let query = ''
    for(const key in componentProps) {
      if(['layout', 'size', 'min', 'max', 'resizable', 'collapsible'].includes(key)) continue
      
      const value = componentProps[key]
      if(value) {
        query += query ? '&' : '?'
        query += `${key}=${value}`
      }
    }

    return `【${component + query}】`
  }

  function onClick(value) {
    treeViewRef.value.setCurrentKey(value.id)
  }

</script>
<style lang="less" scoped>
  .selected {
    border: 1px solid red;
    max-width: calc(100% - 3px);
    max-height: calc(100% - 3px);
  }
</style>